/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.fee.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.PrimaryGenerater;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.mapper.JsonMapper;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.fee.entity.*;
import com.jeeplus.modules.fee.service.*;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 收款单Controller
 * @author weisong
 * @version 2017-09-22
 */
@Controller
@RequestMapping(value = "${adminPath}/fee/bill")
public class BillController extends BaseController {

	@Autowired
	private BillService billService;
	@Autowired
	private BillReceiveDetailService billReceiveDetailService;
	@Autowired
	private BillDetailService billDetailService;
	@Autowired
	private OpenInvoiceService openInvoiceService;
	@Autowired
	private OpenInvoiceDetailService openInvoiceDetailService;
	@Autowired
	private ReceivablesService receivablesService;
	@Autowired
	private ConsignorService consignorService;

	@ModelAttribute
	public Bill get(@RequestParam(required=false) String id) {
		Bill entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = billService.get(id);
		}
		if (entity == null){
			entity = new Bill();
		}
		return entity;
	}
	
	/**
	 * 收款单列表页面
	 */
	@RequiresPermissions("fee:bill:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/fee/billList";
	}
	
		/**
	 * 收款单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("fee:bill:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Bill bill, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Bill> page = billService.findPage(new Page<Bill>(request, response), bill); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑收款单表单页面
	 */
	@RequiresPermissions(value={"fee:bill:view","fee:bill:add","fee:bill:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Bill bill, Model model) {
		model.addAttribute("bill", bill);
		//查询关联收款单-结算单明细表的数据
		if(null != bill.getId()){
			BillReceiveDetail fbrd = new BillReceiveDetail();
			fbrd.setFeeBill(bill);
			List<BillReceiveDetail> billReceiveDetails = billReceiveDetailService.findList(fbrd);
			model.addAttribute("billReceiveDetails", billReceiveDetails);
			model.addAttribute("sign", "sign");
		}
		//与收款单子表关查询收款单主表联的的数据
		List<BillDetail> list = billDetailService.findBillDetailById(bill.getId());
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		model.addAttribute("target",request.getParameter("target"));
		if(null!=list && list.size()>0){
			model.addAttribute("list", list);
			model.addAttribute("flag","feeBill");
		}else{
			if(null != request.getParameter("ids")){
				List<OpenInvoiceDetail> allNewInvoice = new ArrayList<OpenInvoiceDetail>();
				String ids[] = request.getParameter("ids").split(",");
				System.out.println(ids);
				if(null != ids || ids.length != 0){
					//传过来的发票主表id
					for(String id : ids){
						OpenInvoice invoice = openInvoiceService.get(id);
						//根据发票主表id获取发票子表
						OpenInvoiceDetail temp = new OpenInvoiceDetail();
						temp.setFeeOpenInvoice(invoice);
						List<OpenInvoiceDetail> invoiceDetails = openInvoiceDetailService.findList(temp);
						for (OpenInvoiceDetail invoiceDetail : invoiceDetails) {
							//获取收款单子表
							List<BillDetail> details = billDetailService.findAllBillDetailById(invoiceDetail.getId());
							Double vcaMoney = 0.0;
							for( BillDetail detail : details ){
								vcaMoney += detail.getTheVcaMoney();
							}
							invoiceDetail.setVcaMoney(vcaMoney);
							allNewInvoice.add(invoiceDetail);
						}
					}
					model.addAttribute("list", allNewInvoice);
				}
			}
		}
		return "modules/fee/billForm";
	}

	/**
	 * 保存收款单
	 */
	@RequiresPermissions(value={"fee:bill:add","fee:bill:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(Bill bill, Model model,HttpServletRequest request,  RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, bill)){
			return form(bill, model);
		}
		if(!bill.getIsNewRecord()){//编辑表单保存
			Bill t = billService.get(bill.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(bill, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			billService.save(t);//保存

			//将结算单的数据保存到收款单子表
			String ids_receivable = request.getParameter("ids_payable");	//接收表单的值
			if(StringUtils.isNotEmpty(ids_receivable)){
				//保存收款单子表
				saveReceivable(bill,ids_receivable);
				//引入结算单保存时对结算单的回填
				if(bill.getStatus() != 0){
					BackFillReceivableStatusAndMoney(bill);
				}
			}

			//保存到收款单明细表
			BillDetail fbd = null;
			String[] _ids = request.getParameter("ids").split(",");	//将form页面取的id值循环遍历
			//本次核销总金额
			double theVcaMoney = 0.0;
			System.out.println("本次核销总金额:"+theVcaMoney);
			if (_ids.length != 0) {
				for (String id : _ids) {
					if (StringUtils.isNotEmpty(id)) {
						double vcaMoney = 0.0;
						fbd = new BillDetail();
						String[] str = id.split("_"); // 1232323 20032323 456[发票id 发票明细id// 本次核销金额]
						if (StringUtils.isNotEmpty(str[0])) {
							//获取应开发票主表
							OpenInvoice invoice = openInvoiceService.get(str[0]);
							fbd.setFeeOpenInvoice(invoice);
							fbd.setInvoiceNo(invoice.getEntityNo());
						}
						if (StringUtils.isNotEmpty(str[1])) {
							//获取应开发票子表
							OpenInvoiceDetail invoiceDetail = openInvoiceDetailService.get(str[1]);
							if(invoiceDetail == null){
								continue;
							}
							fbd.setFeeOpenInvoiceDetail(invoiceDetail);
							fbd.setInvoiceMoney(invoiceDetail.getInvMoney());
							if (null == invoiceDetail.getFeeOpenInvoice().getVcaMoney()) {
								fbd.setVcaMoney(0.0);
							} else {
								//根据发票主表id获取收款单子表
								List<BillDetail> billDetail = billDetailService.findList(fbd);
								for (int i = 0; i < billDetail.size(); i++) {
									BillDetail bd = billDetail.get(i);
									vcaMoney += bd.getTheVcaMoney();
								}
								fbd.setVcaMoney(vcaMoney);
							}
						}
						if (StringUtils.isNotEmpty(str[2])) {
							fbd.setTheVcaMoney(Double.parseDouble(str[2]));
							theVcaMoney +=Double.parseDouble(str[2]);
						}
						fbd.setFeeBill(bill);
						billDetailService.save(fbd);
					}
				}
			}
			addMessage(redirectAttributes, "保存收款单成功");
		}else{//新增表单保存
			//生成单号
			String number="";
			Bill bills = billService.findBillNoAndBillDate();
			Format format1 = new SimpleDateFormat("yyyyMMdd");  	//初始化时间格式
			//比较结算日期是否和现在的日期相等
			if (null == bills) {
				number = PrimaryGenerater.getInstance().generaterNextNumber("SKDH", null);
			} else {
				if (String.valueOf(format1.format(bills.getBillDate())).equals(String.valueOf(format1.format(new Date())))) {
					number = PrimaryGenerater.getInstance().generaterNextNumber("SKDH", bills.getBillNo());
				} else {
					number = PrimaryGenerater.getInstance().generaterNextNumber("SKDH", null);
				}
			}
			bill.setBillNo(number);
			String ids= request.getParameter("ids");	//将form页面取的id值循环遍历
			if(StringUtils.isEmpty(ids) || StringUtils.isEmpty(ids.trim().replaceAll(",",""))){
				//手动输入的收款金额,没有引入子表
				bill.setOperateType(Bill.noDetail);
				billService.save(bill);//保存
			}else{
				//引入后，累加明细自动填写的收款金额
				bill.setOperateType(Bill.haveDetail);
				//根据结算方名称查询id
				Consignor feeConsignor = consignorService.findUniqueByProperty("name",bill.getPayerName().getName());
				bill.setPayerName(feeConsignor);
				billService.save(bill);//保存
				//保存收款单明细表
				if(StringUtils.isNotEmpty(ids)){
					saveBillDetail(ids,bill);
				}
			}

			//将结算单的数据保存到收款单子表
			String ids_receivable = request.getParameter("ids_payable");	//接收表单的值
			if(StringUtils.isNotEmpty(ids_receivable)){
				//根据结算方名称查询id
				Consignor feeConsignor = consignorService.findUniqueByProperty("name",bill.getPayerName().getName());
				bill.setPayerName(feeConsignor);
				billService.save(bill);//保存
				//保存收款单子表
				saveReceivable(bill,ids_receivable);
			}
			addMessage(redirectAttributes, "保存收款单成功");
			String type = request.getParameter("typeTarget");
			System.out.println(type);
			if(null != type){
				if(type.equals("invoice")) {
					return "redirect:" + Global.getAdminPath() + "/fee/openInvoice/?repage";
				}else{
					return "redirect:"+Global.getAdminPath()+"/fee/bill/?repage";
				}
			}
		}

		return "redirect:"+Global.getAdminPath()+"/fee/bill/?repage";
	}
	
	/**
	 * 删除收款单
	 */
	@ResponseBody
	@RequiresPermissions("fee:bill:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Bill bill, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		billService.delete(bill);
		j.setMsg("删除收款单成功");
		return j;
	}
	
	/**
	 * 批量删除收款单
	 */
	@ResponseBody
	@RequiresPermissions("fee:bill:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			//删除收款单时删除子表数据
			BillDetail temp = new BillDetail();
			temp.setFeeBill(billService.get(id));
			List<BillDetail> list = billDetailService.findList(temp);
			for (int i = 0; i < list.size(); i++) {
				//删除收款单明细表
				billDetailService.delete(list.get(i));
			}
			billService.delete(billService.get(id));
		}
		j.setMsg("删除收款单成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("fee:bill:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Bill bill, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "收款单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Bill> page = billService.findPage(new Page<Bill>(request, response, -1), bill);
    		new ExportExcel("收款单", Bill.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出收款单记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("fee:bill:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Bill> list = ei.getDataList(Bill.class);
			for (Bill bill : list){
				try{
					billService.save(bill);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条收款单记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条收款单记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入收款单失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/bill/?repage";
    }
	
	/**
	 * 下载导入收款单数据模板
	 */
	@RequiresPermissions("fee:bill:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "收款单数据导入模板.xlsx";
    		List<Bill> list = Lists.newArrayList(); 
    		new ExportExcel("收款单数据", Bill.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/bill/?repage";
    }

	/**
	 * 根据收款单主表id查询子表数据
	 * @return
	 */
	@RequestMapping(value = "findBillReceiveDetailByBillId")
	public @ResponseBody
	List<BillReceiveDetail> findBillReceiveDetailByBillId(HttpServletRequest request){
		String billId = request.getParameter("id");
		List<BillReceiveDetail> list = new ArrayList<BillReceiveDetail>();
		BillReceiveDetail detail = new BillReceiveDetail();
		if(StringUtils.isNotEmpty(billId)){
			//获取主表数据
			Bill feeBill = billService.get(billId);
			detail.setFeeBill(feeBill);
			//获取子表数据
			list = billReceiveDetailService.findList(detail);
		}
		return list;
	}

	/**
	 * 获取弹出窗口的数据
	 */
	@RequestMapping(value="findOpenInvoiceList")
	public @ResponseBody
	List<OpenInvoice> findList(OpenInvoice feeOpenInvoice, HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes){
		// 判断引入明细的状态是否为全部核销
		String _status = request.getParameter("status");
		//获取查询框输入的值[模糊查询]
		String clearUnit = request.getParameter("clearUnit");
		if (_status != null) {
			Integer status = Integer.parseInt(_status);
			feeOpenInvoice.setStatus(status);
		}
		if(StringUtils.isNotEmpty(clearUnit)){
			feeOpenInvoice.setInvoiceObj(clearUnit);//结算方
		}
		//获取结算单的值
		String billIds = request.getParameter("billIds");
		List<OpenInvoice> list = new ArrayList<OpenInvoice>();
		//结算单id
		if (StringUtils.isNotEmpty(billIds)) {
			String[] ables = billIds.split(",");
			if (ables.length > 0) {
				for (String ableId : ables) {
					feeOpenInvoice.setFeeReceivables(ableId);
					List<OpenInvoice>  list1 =  openInvoiceService.findList(feeOpenInvoice);
					list.addAll(list1);
				}
			}
		} else{
			list  = openInvoiceService.findList(feeOpenInvoice);
		}
		return list;
	}

	/**
	 * 删除收款单明细
	 * @param id 收款单子表id
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "removeFeeBillDetail")
	public String removeFeeBillDetail(String id, RedirectAttributes redirectAttributes) {
		BillDetail feeBillDetail = billDetailService.get(id);	//根据id查询数据
		//获取本次核销金额
		Double theVcaMoney = feeBillDetail.getTheVcaMoney();
		//获取收款单主表
		Bill feeBill = billService.get(feeBillDetail.getFeeBill());
		//获取收款单的总收款金额
		Double paymentMoney = feeBill.getBillMoney();
		//更新收款单主表的收款金额
		if (null != theVcaMoney && null != paymentMoney) {
			feeBill.setBillMoney((paymentMoney-theVcaMoney));
			billService.save(feeBill);
		}
		billDetailService.delete(feeBillDetail);
		addMessage(redirectAttributes, "删除收款单明细成功");
		return "redirect:"+Global.getAdminPath()+"/fee/bill/form?id="+feeBill.getId();
	}

	/**
	 * 修改状态
	 * @return
	 */
	@RequestMapping(value = "updateStatusTwo")
	public @ResponseBody AjaxJson updateStatusTwo(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray) {
			//获得收款单主表
			Bill feeBill = billService.get(id);
			//更新状态
			if (feeBill.getStatus() < Bill.updateStatus3) {
				billService.updateStatusById(Bill.updateStatus3, id);
			}
			//查询收款单子表
			BillDetail fbd = new BillDetail();
			fbd.setFeeBill(feeBill);
			List<BillDetail> feeBillDetail = billDetailService.findList(fbd);
			if (feeBillDetail.size() > 0) {
				//调用回填发票和结算单方法
				BackFillOperations(feeBill);
			}
			//查询收款单-结算单子表
			BillReceiveDetail fbr = new BillReceiveDetail();
			fbr.setFeeBill(feeBill);
			List<BillReceiveDetail> feeBillReceiveDetail = billReceiveDetailService.findList(fbr);
			if (feeBillReceiveDetail.size() > 0) {
				//调用回填结算单，修改状态和核销金额
				BackFillReceivableStatusAndMoney(feeBill);
			}
		}
		j.setMsg("收款单状态修改成功");
		return j;

	}
	/**
	 * 修改状态
	 * @param id 收款单主表id
	 * @param type 判断页面请求路径 form:跳转到form页面 list:跳转到list页面
	 * @return
	 */
	@RequestMapping(value = "updateStatus")
	public String updateStatus(String id,@RequestParam(value="type")String type) {
		if(StringUtils.isEmpty(id)){
			return "redirect:"+Global.getAdminPath()+"/fee/bill/?repage";
		}
		//获得收款单主表
		Bill feeBill = billService.get(id);
		//更新状态
		if(feeBill.getStatus() < Bill.updateStatus3){
			billService.updateStatusById(Bill.updateStatus3, id);
		}
		//查询收款单子表
		BillDetail fbd = new BillDetail();
		fbd.setFeeBill(feeBill);
		List<BillDetail> feeBillDetail = billDetailService.findList(fbd);
		if(feeBillDetail.size()>0){
			//调用回填发票和结算单方法
			BackFillOperations(feeBill);
		}
		//查询收款单-结算单子表
		BillReceiveDetail fbr = new BillReceiveDetail();
		fbr.setFeeBill(feeBill);
		List<BillReceiveDetail> feeBillReceiveDetail = billReceiveDetailService.findList(fbr);
		if(feeBillReceiveDetail.size()>0){
			//调用回填结算单，修改状态和核销金额
			BackFillReceivableStatusAndMoney(feeBill);
		}
		if(type.equals("form")){
			return "redirect:"+Global.getAdminPath()+"/fee/bill/form?id="+id;
		}else{
			return "redirect:"+Global.getAdminPath()+"/fee/bill/?repage";
		}
	}

	/**
	 * 回填发票和结算单
	 * @param feeBill 收款单主表
	 */
	public void BackFillOperations(Bill feeBill){
		//获得收款单子表list
		BillDetail temp = new BillDetail();
		temp.setFeeBill(feeBill);
		List<BillDetail> fbds = billDetailService.findList(temp);
		if (null != fbds && fbds.size() > 0) {
			for (BillDetail fbDetail : fbds) {
				//开始回填应开发票的核销金额,判断开票金额与核销金额是否相等并改变状态
				//获得发票主表
				OpenInvoice feeOpenInvoice = openInvoiceService.get(fbDetail.getFeeOpenInvoice());
				//获取发票主表已核销金额[如果已核销金额为空，则设置为0]
				double vacMoney = feeOpenInvoice.getVcaMoney()==null?0.0:feeOpenInvoice.getVcaMoney();
				vacMoney += (fbDetail.getTheVcaMoney()==null?0.0:fbDetail.getTheVcaMoney());
				//更新核销金额和状态
				if (vacMoney == feeOpenInvoice.getInvoiceMoney()) {
					openInvoiceService.updateVcaMoneyAndStatusById(vacMoney, OpenInvoice.updateStatus2, feeOpenInvoice.getId());
				} else if (vacMoney < feeOpenInvoice.getInvoiceMoney() && vacMoney > 0) {
					openInvoiceService.updateVcaMoneyAndStatusById(vacMoney, OpenInvoice.updateStatus1, feeOpenInvoice.getId());
				}

				//开始回填应收结算单的核销金额，收款金额(与核销金额相等)并改变状态
				//获得发票子表，根据发票子表获得应收结算单
				Receivables receivable = receivablesService.findByBillDetailId(fbDetail.getId());
				double ableVca = receivable.getVcaMoney()==null?0.0:receivable.getVcaMoney();
				ableVca += (fbDetail.getTheVcaMoney()==null?0.0:fbDetail.getTheVcaMoney());
				//更新核销金额和状态[判断核销金额是否等于结算金额]
				if (ableVca == receivable.getPayMoney()) {
					receivablesService.updateStatusAndMoneyById(Receivables.updateStatus5, null, ableVca,
							null,0.0, receivable.getId());
				} else if (ableVca < receivable.getPayMoney() && ableVca > 0) {
					receivablesService.updateStatusAndMoneyById(Receivables.updateStatus4, null, ableVca,
							null,receivable.getPayMoney()-ableVca, receivable.getId());
				}
			}
		}
	}

	/**
	 * 收款单引入结算单更新结算单的状态和核销金额
	 */
	public void BackFillReceivableStatusAndMoney(Bill feeBill) {
		//根据收款单主表查询收款单--结算单子表
		BillReceiveDetail feeBillReceiveDetail = new BillReceiveDetail();
		feeBillReceiveDetail.setFeeBill(feeBill);
		List<BillReceiveDetail> billDetails = billReceiveDetailService.findList(feeBillReceiveDetail);
		//循环遍历收款单--结算单明细表，根据应收结算单属性更新结算单
		if (billDetails.size() > 0) {
			for (BillReceiveDetail frd : billDetails) {
				//结算金额
				Double clearMoney = frd.getClearingMoney()== null ? 0.0 : frd.getClearingMoney();
				//获取本次核销金额
				Double theVca = frd.getTheVcaMoney() == null ? 0.0 : frd.getTheVcaMoney();
				//查询结算单主表
				Receivables receivables = receivablesService.get(frd.getFeeReceivables().getId());
				//获取结算单的核销金额
				Double vca = receivables.getVcaMoney()== null ? 0.0 : receivables.getVcaMoney();
				//获取结算单的开票金额
				Double inv = receivables.getInvoiceMoney()== null ? 0.0 : receivables.getInvoiceMoney();
				if ((theVca+vca) < clearMoney) {
					//根据结算单id更新结算单的状态和核销金额[状态，开票金额，核销金额，未开票金额，未核销金额，id]
					receivablesService.updateStatusAndMoneyById(Receivables.updateStatus4, inv,
							(theVca+vca), (clearMoney-inv), (clearMoney - (theVca+vca)), receivables.getId());
				}else{
					receivablesService.updateStatusAndMoneyById(Receivables.updateStatus5, inv,
							(theVca+vca), (clearMoney-inv), 0.0, receivables.getId());
				}
			}
		}
	}

	/**
	 * 收款单form页面引入明细按钮时的确定
	 */
	@RequestMapping(value = "addFeeBill")
	public @ResponseBody String addFeeBill(@RequestParam String ids, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		List<OpenInvoiceDetail> list = new ArrayList<OpenInvoiceDetail>();
		if (StringUtils.isNotEmpty(ids)) { // 判断ids是否为空
			String[] _ids = ids.split(",");
			for (String id : _ids) {
				if (StringUtils.isNotEmpty(id)) {
					OpenInvoiceDetail tempDetail = new OpenInvoiceDetail();
					//根据发票id获取发票主表
					OpenInvoice invoice = openInvoiceService.get(id);
					tempDetail.setFeeOpenInvoice(invoice);
					//根据发票获取发票子表
					List<OpenInvoiceDetail> invoiceDetails = openInvoiceDetailService.findList(tempDetail);
					for (OpenInvoiceDetail invoiceDetail : invoiceDetails) {
						//获取收款单子表
						List<BillDetail> details = billDetailService.findAllBillDetailById(invoiceDetail.getId());
						//获取本次核销金额
						Double vcaMoney = 0.0;
						for( BillDetail detail : details ){
							vcaMoney += detail.getTheVcaMoney();
						}
						//设置引入发票时的已核销金额
						invoiceDetail.setVcaMoney(vcaMoney);
					}
					list.addAll(invoiceDetails);
				}
			}
		}
		return JsonMapper.toJsonString(list);
	}

	/**
	 * 保存收款单明细表
	 */
	public void saveBillDetail(String ids,Bill feeBill){
		String[] _ids = ids.split(",");	//将form页面取的id值循环遍历
		//保存到收款单明细表
		BillDetail fbd = null;
		if (_ids.length != 0) {
			for (String id : _ids) {
				if (StringUtils.isNotEmpty(id)) {
					double vcaMoney = 0.0;
					fbd = new BillDetail();
					String[] str = id.split("_"); // 1232323 20032323 456[发票id 发票明细id// 本次核销金额]
					if (StringUtils.isNotEmpty(str[0])) {
						//获取应开发票主表
						OpenInvoice invoice = openInvoiceService.get(str[0]);
						fbd.setFeeOpenInvoice(invoice);
						fbd.setInvoiceNo(invoice.getEntityNo());
					}
					if (StringUtils.isNotEmpty(str[1])) {
						//获取应开发票子表
						OpenInvoiceDetail invoiceDetail = openInvoiceDetailService.get(str[1]);
						fbd.setFeeOpenInvoiceDetail(invoiceDetail);
						fbd.setInvoiceMoney(invoiceDetail.getInvMoney());
						if (null == invoiceDetail.getFeeOpenInvoice().getVcaMoney()) {
							fbd.setVcaMoney(vcaMoney);
						} else {
							//根据发票主表id获取收款单子表
							List<BillDetail> billDetail = billDetailService.findList(fbd);
							for (int i = 0; i < billDetail.size(); i++) {
								BillDetail bd = billDetail.get(i);
								vcaMoney += bd.getTheVcaMoney();
							}
							fbd.setVcaMoney(vcaMoney);
						}
					}
					if (StringUtils.isNotEmpty(str[2])) {
						fbd.setTheVcaMoney(Double.parseDouble(str[2]));
					}
					fbd.setFeeBill(feeBill);
					billDetailService.save(fbd);
				}
			}
		}
	}

	/**
	 * 将结算单的数据保存到收款单--结算单子表
	 */
	public void saveReceivable(Bill feeBill,String ids_receivable){
		//分割ids
		String[] _ids = ids_receivable.split(",");
		//循环遍历_ids
		if (_ids.length != 0) {
			for (String id : _ids) {
				//判断id不为空
				if (StringUtils.isNotEmpty(id)) {
					String[] ableIds = id.split("_");//结算单id_本次核销金额
					if(ableIds.length > 0) {
						//根据id获取结算单数据
						Receivables receivable = receivablesService.get(ableIds[0]);
						if(receivable!=null){
							//保存收款单--结算单子表
							BillReceiveDetail feeBillReceiveDetail = new BillReceiveDetail();
							//设置收款单主表
							feeBillReceiveDetail.setFeeBill(feeBill);
							//设置结算单
							feeBillReceiveDetail.setFeeReceivables(receivable);
							feeBillReceiveDetail.setClearingNo(receivable.getClearingNo());
							feeBillReceiveDetail.setBusyDate(receivable.getBusyDate());
							feeBillReceiveDetail.setFeeConsignor(receivable.getPayerName());
							feeBillReceiveDetail.setClearingMoney(receivable.getPayMoney());
							feeBillReceiveDetail.setVcaMoney(receivable.getVcaMoney());
							feeBillReceiveDetail.setTheVcaMoney(Double.parseDouble(ableIds[1]));
							feeBillReceiveDetail.setRemarks(receivable.getRemarks());
							billReceiveDetailService.save(feeBillReceiveDetail);
						}
					}
				}
			}
		}
	}

	/**
	 * 收款单获取结算单弹出窗口的数据
	 */
	@RequestMapping(value = "findAllFeeReceivables")
	public
	@ResponseBody
	List<Receivables> findAllFeeReceivables(HttpServletRequest request, HttpServletResponse response) {
		// 判断应付结算单的状态【已确认】
		String _status = request.getParameter("status");
		//转换为int
		Integer status = Integer.parseInt(_status);
		//获input框输入的值[模糊查询]
		String clearUnit = request.getParameter("clearUnit");
		List<Receivables> list = new ArrayList<Receivables>();
		if (StringUtils.isNotEmpty(clearUnit)) {
			list = receivablesService.findAllByStatus(clearUnit, status);
		} else {
			list = receivablesService.findAllByStatus(null, status);
		}
		return list;
	}

	/**
	 * 删除收款单--结算单明细
	 * @param id 付款单--结算单子表id
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "removebillReceDetail")
	public String removebillReceDetail(String id, RedirectAttributes redirectAttributes) {
		BillReceiveDetail feeBillReceiveDetail = billReceiveDetailService.get(id);	//根据id查询数据
		//获取本次核销金额
		Double theVcaMoney = feeBillReceiveDetail.getTheVcaMoney();
		//获取付款单主表
		Bill feeBill = billService.get(feeBillReceiveDetail.getFeeBill());
		//获取付款单的总付款金额
		Double billMoney = feeBill.getBillMoney();
		//更新付款单主表的付款金额
		if (null != theVcaMoney && null != billMoney) {
			feeBill.setBillMoney((billMoney-theVcaMoney));
			billService.save(feeBill);
		}
		billReceiveDetailService.delete(feeBillReceiveDetail);
		addMessage(redirectAttributes, "删除收款单--结算单明细成功");
		return "redirect:"+ Global.getAdminPath()+"/fee/bill/form?id="+feeBill.getId();
	}

	/**
	 * 收款单引入结算单明细时的确定按钮
	 */
	@RequestMapping(value = "addFeeReceivablesDetails")
	public
	@ResponseBody
	String addFeeReceivablesDetails(@RequestParam String ids, Model model, RedirectAttributes redirectAttributes) {
		//如果ids为空，则跳转到feeReceivablesForm
		String url = "/fee/receivables/?repage";
		List<Receivables> list = new ArrayList<Receivables>();
		if (StringUtils.isNotEmpty(ids)) {    //判断ids是否为空
			String[] _ids = ids.split(",");
			for (String id : _ids) {
				if (StringUtils.isNotEmpty(id)) {
					Receivables receivables = receivablesService.get(id);
					list.add(receivables);
				}
			}
		}
		return JsonMapper.toJsonString(list);
	}




}